<?php

declare(strict_types=1);

namespace app\model\api\admin\system;

use think\facade\Db;
use app\library\api\admin\Auth;
use app\model\api\admin\BaseAdmin;
use think\model\concern\SoftDelete;

class Dept extends BaseAdmin
{
    use SoftDelete;
    protected $globalScope = ['DataScope'];
    public bool $dataScopeOn = true; // 子类可以覆盖这个属性来控制是否启用数据权限

    public const STATUS_DISABLE = 0;
    public const STATUS_NOMAL = 1;

    public static function onBeforeUpdate($model)
    {
        Db::transaction(function () use ($model) {
            // parent_ids 自动生成并更新
            $original = self::find($model->id); // 获取原始数据
            if ($original && $original->parent_id != $model->parent_id) {
                // 设置新的 parent_ids
                if ($model->parent_id > 0) {
                    $parent = self::where('id', $model->parent_id)->find();
                    $model->parent_ids = $parent ? ($parent->parent_ids ? $parent->parent_ids . ',' . $parent->id : $parent->id) : null;
                } else {
                    $model->parent_ids = null;
                }

                // 更新所有子级的 parent_ids
                $oldPath = $original->parent_ids ? $original->parent_ids . ',' . $original->id : $original->id;
                $children = self::where('parent_ids', 'like', $oldPath . '%')->select();
                foreach ($children as $child) {
                    // 替换掉子级 parent_ids 中从当前本级开始的部分
                    $oldPath = $original->parent_ids ? $original->parent_ids . ',' . $original->id : $original->id;
                    $newPath = $model->parent_ids ? $model->parent_ids . ',' . $model->id : $model->id;

                    $child->parent_ids = str_replace($oldPath, $newPath, $child->parent_ids);
                    $child->withEvent(false)->save(); // 禁用事件,避免parent_ids设计因事件而类似递归调用导致达不到预期减少调用
                    // $child->withEvent(true);
                }
            }
        });
    }

    public static function onBeforeInsert($model)
    {
        parent::onBeforeInsert($model);

        if ($model->parent_id > 0) {
            $parent = self::where('id', $model->parent_id)->find();
            $model->parent_ids = $parent ? ($parent->parent_ids ? $parent->parent_ids . ',' . $parent->id : $parent->id) : null;
        }
    }

    public static function onAfterInsert($model)
    {
        // 部门的dept_id 暂不跟从创建者的dept_id
        $model->dept_id = $model->id;
        $model->save();
    }

    public static function onAfterWrite($model)
    {
        // 清理缓存-新增/修改 都可能影响-本部门及以下
        $auth = Auth::instance();
        $auth->clearCache(null, [], ['ADMIN_DATA_SCOPE_TAG']);
    }
}
